package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.smartcard.SmartCardUserAuthPushDTO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.POJO.VO.app.AppDoorDevicesVO;
import com.itlong.cloud.POJO.VO.app.AppFloorDevicesVO;
import com.itlong.cloud.app.service.IAppDeviceService;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.smartcard.service.ISmartCardFaceService;
import com.itlong.cloud.utils.node.JsonUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * <desc>
 * C#人脸识别用户权限信息变更指令推送消费者
 * </desc>
 */
@Component
public class SmartCardFaceUserAuthChangePushConsumer {

    private static final Logger LOG = LoggerFactory.getLogger(SmartCardFaceUserAuthChangePushConsumer.class);

    @Autowired
    IAppDeviceService iAppDeviceService;

    @Autowired
    ISmartCardFaceService iSmartCardFaceService;

    /**
     * <desc>
     * C#人脸识别用户权限信息变更指令推送消费者
     * <desc/>
     *
     * @param message 消息数据
     * @author Juguang.S
     * @createDate 2019/03/20
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_SMARTCARD_FACE_USER_AUTH_CHANGE_PUSH_QUEUE)
    public void process(Message message, Channel channel) throws IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_推送C#人脸识别数据:" + new String(body));
        try {
            TimeTaskDeadMessageQueuePO deadMessageQueuePO = JsonUtil.toObject(new String(body),
                    TimeTaskDeadMessageQueuePO.class);
            JSONObject jsdata = JSONObject.parseObject(deadMessageQueuePO.getMessageContent());
            SmartCardUserAuthPushDTO dto = JsonUtil.toObject(jsdata.get("data").toString(), SmartCardUserAuthPushDTO.class);
            List<Map<String, Object>> auths = new ArrayList<>();
            String deviceUniqueStr = dto.getDeviceUniqueStr();
            String status = dto.getStatus();
            //为了避免下发重复增量，现进行去重处理
            Set<String> sets = new HashSet<>();
            for (String userId : dto.getUserIdList()) {
                sets.add(userId);
            }
            //为了避免此逻辑处理时有些逻辑还没有处理完导致的数据异常问题，在此睡眠90秒，保证设备权限更新方可执行以下操作
//            Thread.sleep(90000);
            for (String userId : sets) {
                List<Map<String, Object>> sysAuths = new ArrayList<>();
                Map<String, Object> auth = new HashMap<>();
                auth.put("userId", userId);
                auth.put("id",userId);
                //如果userId不以V_为前缀则代表为住户 否则为访客
                if(userId.startsWith("V_")){
                    userId = iSmartCardFaceService.getUserIdByVFaceId(userId);
                }

                //门禁
                List<AppDoorDevicesVO> doors = iAppDeviceService.getDoorDevices(userId, dto.getProjectId(), 0);
                for (AppDoorDevicesVO door : doors) {
                    Map<String, Object> sysAuth = new HashMap<>();
                    sysAuth.put("deviceType", 2);
                    sysAuth.put("auth", "8");
                    sysAuth.put("deviceUnique", door.getDeviceUnique());
                    if((StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("3")) ||
                            (StringUtils.isNotBlank(door.getDoorType()) && door.getDoorType().contains("1,3"))){
                        sysAuth.put("isWippen","1");
                    }else{
                        sysAuth.put("isWippen","0");
                    }
                    sysAuths.add(sysAuth);
                }
                //电梯
                List<AppFloorDevicesVO> floorsList = iAppDeviceService.getFloorDevices(userId, dto.getProjectId(), 0);
                for (AppFloorDevicesVO floorInfo : floorsList) {
                    if(iSmartCardFaceService.isCloudElevator(floorInfo.getDeviceUnique())>0){
                        Map<String, Object> sysAuth = new HashMap<>();
                        sysAuth.put("deviceType", 1);
                        sysAuth.put("auth", floorInfo.getLiveFloor());
                        sysAuth.put("deviceUnique", floorInfo.getDeviceUnique());
                        sysAuths.add(sysAuth);
                    }
                }
                auth.put("sysAuths", sysAuths);
                auths.add(auth);
            }
            //如果是设备启用禁用触发的，则需将设备下的访客信息给拼接进来
            if(StringUtils.isNotEmpty(deviceUniqueStr) && StringUtils.isNotEmpty(status)){
                auths = iSmartCardFaceService.saveVisitorInfo(deviceUniqueStr,status,auths, dto.getProjectId());
            }
            iSmartCardFaceService.pushUserAuthChange(JsonUtil.toJSON(auths), dto.getProjectId());
        } catch (Exception e) {
            LOG.error("【RabbitMQ_推送C#人脸识别用户权限信息变更指令推送消费者】:处理异常", e);
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
